<template>
  <div class="app-container">
    <el-form
      v-loading="formLoading"
      :model="postForm"
      :rules="rules"
      ref="postForm"
      label-width="220px"
      label-position="right"
    >
      <el-form-item label="选择类别：">
        <el-radio-group v-model="catLevel" @change="selectCategory" :disabled="catLevelDisabled">
          <el-radio
            v-for="item in categoryOptions"
            :key="item.key"
            :label="item.key"
            :value="item.key"
          >{{ item.value }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="!parentCatShow" label="选择一级类别：" prop="parentId">
        <el-select v-model="postForm.parentId" placeholder="请选择" style="width: 650px">
          <el-option
            v-for="item in parentOptions"
            :key="item.classifyId"
            :label="item.name"
            :value="item.classifyId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="parentCatShow" label="一级类别：" prop="name">
        <el-input v-model.trim="postForm.name" placeholder="请输入一级类别名称，不超过10个字" style="width: 650px"></el-input>
      </el-form-item>
      <!-- <el-form-item v-if="parentCatShow" label="是否首页显示：">
        <el-radio-group v-model="postForm.indexShow">
          <el-radio :label="0">否</el-radio>
          <el-radio :label="1">是</el-radio>
        </el-radio-group>
      </el-form-item> -->
      <el-form-item v-if="!parentCatShow" label="二级类别：" prop="name">
        <el-input v-model.trim="postForm.name" placeholder="请输入二级类别名称，不超过10个字" style="width: 650px"></el-input>
      </el-form-item>
      <!-- <el-form-item label="分类排序：" prop="sort">
        <el-input type="number" v-model.number="postForm.sort" style="width: 650px"></el-input>
      </el-form-item> -->
      <!-- <el-form-item label="分类图片(宽80*高80)："></el-form-item> -->
      <!-- <el-form-item label="状态：">
        <el-checkbox v-model="postForm.status" :true-label=1 :false-label=0>开启(关闭后该分类不能再使用, 该分类下的商品不会下架)</el-checkbox>
      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-check" @click="submitForm">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import {
  getCourseCategory,
  createCourseCategory,
  updateCourseCategory,
  getParentCategories,
  getChildCategories
} from "@/api/courseCategory";
import { Classify,SetClassify,first,GetClassify } from "@/api/member";
// import imageComponent from '@/components/imageComponent'
// import ImageCropper from '@/components/ImageCropper'
import defultImg from "@/assets/defult270.png";
const postForm = {
  name: null,
  parentId: 0,
  sort: 0,
  avatar: "",
  status: 1
};

const validateNumber = (rule, value, callback) => {
  if (value && isNaN(value)) {
    callback("请输入正确的数值");
  } else {
    if (value < 0) {
      callback("请输入正确的数值");
    }
    callback();
  }
};

const rules = {
  name: [
    { required: true, message: "请输入分类名称", trigger: "blur" },
    { max: 10, message: "最多不超过10个字符", trigger: "blur" }
  ],
  sort: [
    { required: true, message: "分类排序不能为空", trigger: "blur" },
    { validator: validateNumber, trigger: "blur" }
  ]
};

const categoryOptions = [
  { key: 0, value: "一级类别" },
  { key: 1, value: "二级类别" }
];

export default {
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  // components: {
  //   imageComponent,
  //   ImageCropper
  // },
  data() {
    return {
      postForm: Object.assign({ indexShow: 0 }, postForm),
      rules,
      formLoading: false,
      parentOptions: [],
      categoryOptions,
      catLevel: 0,
      avatarList: [],
      parentCatShow: true,
      catLevelDisabled: false,
      imageUploadUrl:
        process.env.BASE_API + "/common/courseCategories/imageUpload",
      imagecropperShow: false,
      imagecropperKey: 0
    };
  },
  created() {
    this.initOption();
    this.initData();
  },
  methods: {
    initOption() {
      first()
        .then(res => {
          this.parentOptions.push(...res.data.data);
        })
        .catch(err => {
          console.log(err);
        });
    },
    initData() {
      if (this.isEdit) {
        const catId = this.$route.params.catId;
        this.catLevelDisabled = true;
        GetClassify({id:catId})
          .then(res => {
            this.postForm = res.data.data;
            if (this.postForm.parentId > 0) {
              this.catLevel = 1;
              this.parentCatShow = false;
            } else {
              if (this.postForm.avatar) {
                this.avatarList = [{ url: this.postForm.avatar }];
              }
            }
          })
          .catch(err => {
            console.log(err);
          });
      }
    },
    handleCreate() {
      Classify(this.postForm)
        .then(res => {
          this.$notify({
            title: "提示",
            message: "提交成功!",
            type: "success"
          });

          this.close();
        })
        .catch(err => {
          this.formLoading = false;
          console.log(err);
        });
    },
    handleUpdate() {
      const catId = this.$route.params.catId;
      this.postForm.classifyId = catId
      SetClassify(this.postForm)
        .then(res => {
          this.$notify({
            title: "提示",
            message: "提交成功!",
            type: "success"
          });

          this.close();
        })
        .catch(err => {
          this.formLoading = false;
          console.log(err);
        });
    },
    redirectTo() {
      this.$router.push({ name: "courseCategory" });
    },
    submitForm() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          if (!this.postForm.name) {
            this.$message.warning("请填写分类名称");
            return false;
          }
          this.formLoading = true;
          if (this.isEdit) {
            this.handleUpdate();
          } else {
            this.handleCreate();
          }
        } else {
          console.log("error submit!");
          return false;
        }
      });
    },
    submitUpload() {
      this.$refs.upload.submit();
    },

    setDefultImg(e) {
      e.target.src = defultImg;
    },

    selectCategory(val) {
      this.postForm = {
        name: null,
        parentId: 0,
        sort: 0,
        avatar: "",
        status: 1
      };
      this.avatarList = [];
      this.$refs.postForm.clearValidate();

      if (val == 0) {
        // 一级分类
        this.parentCatShow = true;
        this.postForm.avatar = "";
      } else {
        this.parentCatShow = false;
        if (this.postForm.parentId == 0) {
          this.postForm.parentId = this.parentOptions[0].catId;
        }
      }
    },
    close() {
      this.$store.dispatch("delVisitedViews", this.$route).then(views => {
        const latestView = views.slice(-1)[0];
        if (latestView) {
          this.$router.push({ name: "professionCategory" }); // latestView.path
        } else {
          this.$router.push("/");
        }
      });
    }
  }
};
</script>
